package org.cocos2dx.javascript;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Gravity;


import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.vivo.mobilead.banner.BannerAdParams;
import com.vivo.mobilead.banner.VivoBannerAd;
import com.vivo.mobilead.model.BackUrlInfo;
import com.vivo.unionsdk.open.VivoAccountCallback;
import com.vivo.unionsdk.open.VivoExitCallback;
import com.vivo.unionsdk.open.VivoRealNameInfoCallback;
import com.vivo.unionsdk.open.VivoRoleInfo;
import com.vivo.unionsdk.open.VivoUnionSDK;
import com.vivo.mobilead.listener.IAdListener;

import android.view.View;

import com.vivo.mobilead.model.VivoAdError;
import com.vivo.mobilead.util.VOpenLog;

import org.cocos2dx.lib.Cocos2dxJavascriptJavaBridge;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class WDNativePlatform extends Activity {
    private RelativeLayout mRlBannerBottom;
    private VivoBannerAd mBottomVivoBannerAd;
    private String TAG = Config.TAG;
    private static WDNativePlatform instance;
    public AppActivity app = null;
    private Context context = null;
    private String jsStr = "";
    private String useName = "";
    private static String androidId = "";
    public LinearLayout mBannerContainer;
    private WDNativePlatform () {}
    public static WDNativePlatform getInstance() {
        if (instance == null) {
            instance = new WDNativePlatform();
        }
        return instance;
    }
    //==============================================初始化============================================//
    public void initApp (AppActivity _app) {
        app = _app;
        WDNativePlatform.getInstance().loginRes();

    }
    //================================================网动==============================================//
    public static  void customEvent(String event){
        Log.d(Config.TAG, "customEvent"+event);
         //==========>customEvent
    }

    public static void onExit() {
        Log.d(Config.TAG, "onExit");
        WDNativePlatform.getInstance().exit();
    }
    public static void login() {
        Log.d(Config.TAG, "==========login==============");
       VivoUnionSDK.login(WDNativePlatform.getInstance().app);
    }

    public static void showAd() {
        VideoActivity.getInstance().playVideoAd();
    }

    public static void showFullVideo() {

    }
    public static void showFeedAd() {

    }
    public static void hideFeedAd() {

    }
    private void displayBannerAd() {
        if(InterstitialActivity.getInstance().show){
            return;
        }
       app.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mBannerContainer.setVisibility(View.VISIBLE);
                Log.d(Config.TAG, "==========showBannerAd");
            }
        });
    }
    private void loadBanner() {
        mBottomVivoBannerAd = new VivoBannerAd(app, getBuilder().build(), mBottomIAdListener);
        app.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                View adView = mBottomVivoBannerAd.getAdView();
                if (null != adView) {
                    if(mBannerContainer.getChildCount()>0){
                        mBannerContainer.removeAllViews();
                    }
                    mBannerContainer.addView(adView);
                }
                Log.d(Config.TAG, "==========loadBanner");
            }
        });
    }
    private void closeBannerAd() {
        app.runOnUiThread(new Runnable() {
            @Override
            public void run() {
               mBannerContainer.setVisibility(View.INVISIBLE);
                Log.d(Config.TAG, "==========hideBannerAd");
            }
        });
    }

    public static void createNativeAd(){
        Log.d(Config.TAG, "static==========createNativeAd");
        InterstitialActivity.getInstance().showAd();
    }
    public static void showBannerAd() {
        WDNativePlatform.getInstance().displayBannerAd();
    }
    public static void hideBannerAd() {
        WDNativePlatform.getInstance().closeBannerAd();
    }

    private IAdListener mBottomIAdListener = new IAdListener() {
        @Override
        public void onAdShow() {
            Log.d(TAG, "onAdShow: banner");
        }

        @Override
        public void onAdFailed(VivoAdError error) {
            Log.d(TAG, "reason: banner" + error);
        }

        @Override
        public void onAdReady() {
            Log.d(TAG, "onAdReady: banner");
        }

        @Override
        public void onAdClick() {
            Log.d(TAG, "onAdClick: banner");
        }

        @Override
        public void onAdClosed() {
            Log.d(TAG, "onAdClosed: banner");
        }
    };

    private BannerAdParams.Builder getBuilder() {
        BannerAdParams.Builder builder = new BannerAdParams.Builder(Config.BANNER);
        builder.setRefreshIntervalSeconds(30);
        BackUrlInfo backUrlInfo = new BackUrlInfo("", "我是Banner的 btn_Name");
        builder.setBackUrlInfo(backUrlInfo);
        return builder;
    }

    public void loginFinish (Map result) {
        Log.d(Config.TAG, "loginFinish: wdnativeplatform");
        JSONObject jsonObj = new JSONObject(result);
        String loginData = jsonObj.toString();
        System.out.println("native login finish" + loginData);
        jsStr = "window.wdNativeLoginResult('" + loginData + "')";
        this.callJS();
    }
    public void videoFinish (Map result) {
        JSONObject jsonObj = new JSONObject(result);
        String videoData = jsonObj.toString();
        System.out.println("video ad finish" + videoData);
        jsStr = "window.wdNativeVideoResult('" + videoData + "')";
        this.callJS();
    }

    public void test (Map result) {
        String payData = "test";
        System.out.println("native test" + payData);
        jsStr = "window.wdNativeTest('" + payData + "')";
        this.callJS();
    }
    public void callJS () {
        app.runOnGLThread(new Runnable() {
            @Override
            public void run() {
                Cocos2dxJavascriptJavaBridge.evalString(jsStr);
            }
        });
    }

    public void loginRes() {
        VivoUnionSDK.registerAccountCallback(WDNativePlatform.getInstance().app, new VivoAccountCallback() {
            @Override
            public void onVivoAccountLogin(String userName, String openId, String authToken) {
                Map m=new HashMap();
                m.put("result","success");
                m.put("userId",openId);
                WDNativePlatform.getInstance().useName=userName;
                Log.d(Config.TAG, "==========login==============");
                WDNativePlatform.getInstance().getRealNameInfo(m);
            }

            @Override
            public void onVivoAccountLogout(int i) {
                exitLogin();
            }

            @Override
            public void onVivoAccountLoginCancel() {
                exitLogin();
            }
        });
    }
    public void exitLogin(){
        VivoUnionSDK.exit(WDNativePlatform.getInstance().app, new VivoExitCallback() {
            @Override
            public void onExitCancel() {
                //取消退出
                VivoUnionSDK.login(WDNativePlatform.getInstance().app);
            }
            @Override
            public void onExitConfirm() {
                //确认退出
                WDNativePlatform.getInstance().app.finish();
            }
        });
    }
    public static void register(){

    }
    public static void loginSuccess(String jsStr){
        Log.d(Config.TAG, "LoginSuccess"+jsStr);
        String[] splitStr=jsStr.split("&");
        VivoUnionSDK.reportRoleInfo(new VivoRoleInfo(splitStr[1],splitStr[0],WDNativePlatform.getInstance().useName,"1","九天揽月"));
    }

    public static void  getRealNameInfo(final Map m){
        VivoUnionSDK.getRealNameInfo(WDNativePlatform.getInstance().app, new VivoRealNameInfoCallback() {
            @Override
            public void onGetRealNameInfoSucc(boolean isRealName, int age) {
                //isRealName是否已实名制，age为年龄信息，请根据这些信息进行防沉迷操作
                Log.d(Config.TAG,"获取实名认证结果");
                Log.d(Config.TAG,isRealName + "");
                if(isRealName){
                    if(age<18){
                        m.put("isUnderage","true");
                    }
                    else {
                        m.put("isUnderage","false");
                    }
                }
                else {
                    m.put("isUnderage","true");
                }
                WDNativePlatform.getInstance().startGame();
                WDNativePlatform.getInstance().loginFinish(m);
            }

            @Override
            public void onGetRealNameInfoFailed() {
                //获取实名制信息失败，请自行处理是否防沉迷
                m.put("isUnderage","true");
                WDNativePlatform.getInstance().startGame();
                WDNativePlatform.getInstance().loginFinish(m);
            }
        });
    }

    public void exit(){
        VivoUnionSDK.exit(WDNativePlatform.getInstance().app, new VivoExitCallback() {
            @Override
            public void onExitCancel() {
                //取消退出
                Log.d(Config.TAG, "333333333333333333333");
            }
            @Override
            public void onExitConfirm() {
                //确认退出
                WDNativePlatform.getInstance().app.finish();
                Log.d(Config.TAG, "444444444444444444444444");
            }
        });
    }
    public void startGame(){
        VideoActivity.getInstance().initApp(app,app);
        InterstitialActivity.getInstance().initApp(app,app);
        mBannerContainer = new LinearLayout(app.getApplicationContext());
        mBannerContainer.setOrientation(LinearLayout.VERTICAL);
        FrameLayout.LayoutParams params=new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.WRAP_CONTENT);
        params.gravity= Gravity.BOTTOM;
        app.addContentView(mBannerContainer,params);
        mBannerContainer.setVisibility(View.INVISIBLE);
        loadBanner();
        Timer _timer=new Timer();
        TimerTask _task=new TimerTask() {
            @Override
            public void run() {
                loadBanner();
            }
        };
        _timer.scheduleAtFixedRate(_task,30000,30000);
    }
}
